{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### collection.namedtuple()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Subscriber(addr='jonesy@example.com', joined='2012-10-19')\n",
      "jonesy@example.com\n",
      "2012-10-19\n"
     ]
    }
   ],
   "source": [
    "from collections import namedtuple\n",
    "Subscriber = namedtuple('Subscriber', ['addr', 'joined'])\n",
    "sub = Subscriber('jonesy@example.com', '2012-10-19')\n",
    "print(sub)\n",
    "print(sub.addr)\n",
    "print(sub.joined)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 将代码同它所控制的元素位置间解耦"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Stock = namedtuple('Stock', ['name', 'shares', 'price'])\n",
    "\n",
    "def compute_cost(records):\n",
    "    total = 0.0\n",
    "    for rec in records:\n",
    "        s = Stock(*rec)\n",
    "        total += s.shares * s.price\n",
    "    return total"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 命名元组的`_replace()`方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Stock(name='ACME', shares=100, price=123.45)\n",
      "Stock(name='ACME', shares=100, price=123.45)\n"
     ]
    }
   ],
   "source": [
    "# namedtuple()创建的对象为不可变对象，无法通过 `.`进行内容修改\n",
    "# 使用`_replace`可以对namedtuple对象进行修改\n",
    "# 模拟一个命名元组的模板，通过这个模板可以反复生成新的命名元组\n",
    "\n",
    "Stock = namedtuple('Stock', ['name', 'shares', 'price'])\n",
    "\n",
    "# create a prototype instance\n",
    "stock_prototype = Stock('', 0, 0.0,)\n",
    "\n",
    "def dict_to_stock(s):\n",
    "    return stock_prototype._replace(**s)\n",
    "\n",
    "a = {'name': 'ACME', 'shares': 100, 'price': 123.45}\n",
    "print(dict_to_stock(a))\n",
    "b = {'name': 'ACME', 'shares': 100, 'price': 123.45}\n",
    "print(dict_to_stock(b))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.7.4 64-bit",
   "language": "python",
   "name": "python37464bit0eab7a6caf29454899b876d50238c56e"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
